package com.h3bpm.starcharge.controller;

import OThinker.H3.Controller.MvcSheet.MvcPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;

@Controller("printController")
@RequestMapping("/Portal/print")
@Scope("prototype")
public class PrintController extends MvcPage {
    @RequestMapping("/parseHtml")
    @ResponseBody
    public String parseHtml(HttpServletRequest request, HttpServletResponse response, String printContent) {
        //html模板地址
        String projectPath =  request.getSession().getServletContext().getRealPath("/");
        String htmlPath = projectPath+"\\Portal\\sheetPrint.html";
        //打印表单html临时存储地址，第一次需手动新增printTemp
        String printTempPath = projectPath+"\\Portal\\printTemp\\";
        //打印表单html访问url
        String url = "http://118.190.209.10:8080/Portal/printTemp/";

        String templateContent = "";
        // 读取模板文件
        FileInputStream fileinputstream = null;
        try {
            fileinputstream = new FileInputStream(htmlPath);
            int lenght = fileinputstream.available();
            byte[] bytes = new byte[lenght];
            fileinputstream.read(bytes);
            fileinputstream.close();
            templateContent = new String(bytes);
            templateContent = templateContent.replaceAll("###printContent###", Matcher.quoteReplacement(printContent));

            //生成6位随机数
            int randomNum = (int) ((Math.random()*9+1)*100000);
            //生成文件名
            String fileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS") + randomNum + ".html";
            // 建立文件输出流
            FileOutputStream fileoutputstream = new FileOutputStream(printTempPath +"/" + fileName);
            byte[] tagBytes = templateContent.getBytes();
            fileoutputstream.write(tagBytes);
            fileoutputstream.close();

            Map<String, String> temp = new HashMap<>(1);
            temp.put("url", url+fileName);
            ObjectMapper result = new ObjectMapper();
            return result.writeValueAsString(temp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
